let app = getApp()
const util = require('../util/util.js')
Page({
  data: {
    nodata: 'none',
    uuids: [],
    isInspect: false,
    isPatrol: false,
    isSignIn: false,
    isPatrolInsp: false,
    isDutyWeek: false,
    isDutyWeek2: false,
    isSuperior: false,
    inspectlist: [],
    features: '',
    loading: 1,
    stop: 0,
    isElectricalsafetyShow: false,
    isAceessDeviceShow: false,
    locationContent: "请在系统设置-应用权限管理中开启允许微信使用地理位置的开关",
    isSupervising: false,
    isSuddenSupervising: false,
    hsaSafetyInspect: false


  },
  onLoad(e) {
    console.log("首页数据：", app.globalData)


    dd.setNavigationBar({
      title: app.globalData.department,
      backgroundColor: '#108ee9'
    })

    this.setData({
      identity: app.globalData.identityId
    })

    console.log(app.globalData.identityId)

    //游客访问
    if (app.globalData.identityId == "-1" || app.globalData.identityId == "-2") {
      app.globalData.features = ["0"]
      this.middle();
    } else {
      dd.httpRequest({
        headers: {
          "Content-Type": "application/json"
        },
        url: app.baseUrl + '/DingDing/permission/getDingDingFeatures',
        method: 'POST',
        data: JSON.stringify({
          roleId: parseInt(app.globalData.identityId)
        }),

        dataType: 'json',
        success: (res) => {
          app.globalData.features = res.data.key
        },
        complete: () => {
          console.log("数据完成加载！！！")
          this.showIndex()

        }
      })
    }

    //判断是巡更
    if (1 == app.globalData.inspectModel) {
      console.log("巡更判断-------")
      dd.httpRequest({
        headers: {
          "Content-Type": "application/json"
        },
        url: app.baseUrl + '/DingDingSystem2/getSchoolUUIDS',
        method: 'POST',
        data: JSON.stringify({
          schoolId: parseInt(app.globalData.departmentId)
        }),
        dataType: 'json',
        success: (res) => {
          console.log("res-------", res)
          console.log("uuids: ", res.data.uuids)
          this.setData({
            uuids: res.data.uuids.split(",")
          })
          console.log("uuids: ", this.data.uuids)
        }
      })
    }
    //值周
    dd.httpRequest({
      url: app.baseUrl + '/DingDing/DutyWeek/isHasDutyRecoed',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      dataType: 'text',
      data: JSON.stringify({
        schoolId: parseInt(app.globalData.departmentId),
      }),
      success: res => {
        if (res.data == 'fail') {
          this.setData({
            isDutyWeek2: true
          })
        }
      }
    })
  },

  onShow: function (options) {
    //巡查
    this.setData({
      isSupervising: app.globalData.isSupervising,
      isSuddenSupervising: app.globalData.isSuddenSupervising
    })
    this.middle()

  },

  middle: function () {
    console.log("!!!!!!!!!!!!!!!!")
    this.showIndex()
  },


  showIndex: function () {
    console.log("巡检首页")
    //只有教师管理功能 或教师学生用户签到
    if (app.globalData.features == "35" || app.globalData.features == "0") {
      this.setData({
        loading: 0,
        isInspect: true
      })
      return
    }
    if (app.globalData.features.indexOf("37") != -1) {
      this.setData({
        isElectricalsafetyShow: true
      })
    } else {
      this.setData({
        isElectricalsafetyShow: false
      })
    }
    if (app.globalData.features.indexOf("50") != -1) {
      this.setData({
        isDutyWeek: true
      })
    } else {
      this.setData({
        isDutyWeek: false
      })
    }
    if (app.globalData.features.indexOf("42") != -1) {
      this.setData({
        isAceessDeviceShow: true
      })
    } else {
      this.setData({
        isAceessDeviceShow: false
      }) 
    }
    //教育局巡检员
    if (app.globalData.features.indexOf("36") != -1) {
      this.setData({
        isSuperior: true
      })
    } else {
      this.setData({
        isSuperior: false
      })
    }

    // 安全巡查
    if(app.globalData.features.indexOf("129") != -1) {
      this.setData({
        hsaSafetyInspect: true
      })
      // 判断是否有巡查任务正在进行
      this.getStatus()
    } else {
      this.setData({
        hsaSafetyInspect: false
      })
    }


    if (app.globalData.inspectModel != 1) {
      //巡检首页
      dd.httpRequest({
        url: app.baseUrl + '/DingDingSystem2/getInspectItemCategory',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          schoolId: app.globalData.departmentId,
          userId: app.globalData.userId,
          identityId: app.globalData.identityId
        }),
        dataType: 'json',
        success: res => {
          if (res.data.length != 0) {
            let navData = []
            let idxcount = 0
            let categoryIdList = []
            for (let i = 0; i < res.data.length; i++) {
              if (res.data[i].idx != null) {
                navData[i] = res.data[i]
                idxcount++
                categoryIdList.push(res.data[i].categoryId)
              }
              if (res.data[i].undoneNum > 99) {
                res.data[i].undoneNum = '99+'
              }
            }
            dd.setStorageSync({
              key: "navData",
              data: navData
            })
            this.setData({
              // inspectlist: res.data,
              navData: navData,
              idxcount: idxcount,
              categoryIdList: categoryIdList.join(","),
            })
          } else {
            this.setData({
              nodata: 'block'
            })
          }
        },
        fail: res => {
          dd.showToast({
            content: '网络异常！',
            type: 'fail'
          })
        },
        complete: res => {
          this.setData({
            loading: 0,
            isInspect: true
          })
        }
      })
    } else {
      this.setData({
        loading: 0,
        isInspect: true
      })
    }
  },


  toInspectItem(e) {
    console.log("巡检项传过来的id ", e.currentTarget.dataset.id)
    console.log("idxcount: ", this.data.idxcount)
    console.log("categoryIdList: ", this.data.categoryIdList)

    if (e.currentTarget.dataset.id != null) {
      dd.navigateTo({
        url: `/page/inspectItem/inspectItem?id=${e.currentTarget.dataset.id}&idxcount=${this.data.idxcount}&categoryIdList=${this.data.categoryIdList}&currentcategoryId=${e.currentTarget.dataset.categoryId}&categoryName=${e.currentTarget.dataset.categoryName}`,
      })
    } else {
      dd.showToast({
        content: '暂无相关任务',
      })
    }

  },

  toPatrolInsp() {

    let that = this
    dd.showLoading({
      content: '正在搜索设备'
    })
    dd.openBluetoothAdapter({

      //开启蓝牙
      fail: (res) => {
        dd.showToast({
          content: '请开启蓝牙',
          duration: 2000
        })
        setTimeout(function () {
          dd.hideLoading()
        }, 2000)
      },

      success(res) {
        dd.getBluetoothAdapterState({
          success(res) {
            console.log("本机蓝牙状态", res)
          },
          fail(res) {
            console.log("")
          }
        })
        console.log("获取蓝牙成功")
        //获取当前用户的地理位置信息
        dd.getLocation({
          type: 1,
          fail: (res) => {
            //不允许打开定位
            dd.hideLoading()
            //开启系统设置定位
            dd.getSystemInfo({
              success: (res) => {
                if (res.platform == "ios") {
                  that.setData({
                    locationContent: '请在系统设置-微信里开启允许微信使用地理位置的开关'
                  })
                }
                dd.alert({
                  title: '未使用地理位置',
                  content: that.data.locationContent
                })
              },
              fail() {
                dd.alert({
                  title: '未使用地理位置信息',
                  content: that.data.locationContent
                })
              }
            })
          },
          success: (res) => {
            //允许打开定位
            console.log(res)
            //搜索蓝牙设备
            dd.getBluetoothAdapterState({
              success: (res) => {
                let available = res.available
                let discovering = res.discovering

                if (!discovering) {
                  dd.startBluetoothDevicesDiscovery({
                    services: [],
                    //services: [],
                    success: (res) => {
                      dd.hideLoading()
                      console.log("成功搜索到蓝牙", res)
                    }
                  })
                }
              },
              fail: (res) => {
                console.log("获取蓝牙状态失败")
              }
            })
            // dd.startBluetoothDevicesDiscovery({
            //   services: that.data.uuids,
            //   success: (res) => {
            //     console.log("成功搜索到蓝牙", res)
            //   }
            // })

            //获得所有已发现的蓝牙设备
            dd.getBluetoothDevices({
              success: (res) => {
                console.log("获得所有已发现的蓝牙设备", res)
                for (var i = 0; i < res.devices.length; i++) {
                  console.log("蓝牙个数： ", i)
                }
              }
            })


            dd.getConnectedBluetoothDevices({
              services: [],
              success: (res) => {
                console.log("得到连接的蓝牙设备列表： ", res)
              }
            })
          }
        })
      }
    })
  },

  signInMa(e) {

  },


  signInStatistics(e) {

  },

  signdutyweeksatics: util.throttle(function () {
    if (this.data.isDutyWeek2) {
      dd.showToast({
        content: '功能未激活~',
        type: 'fail'
      })
    } else {
      dd.navigateTo({
        url: '/page/dutyweekItem/dutyweekItem',
      })
    }
  }),

  //新增安全排名
  goToSecurityRank: function (e) {
    dd.navigateTo({
      url: `/page/webview/webview?src=${app.preUrl}&type=securityRank&departmentId=${app.globalData.departmentId}`,
    })
  },

  // 判断是否正在巡查
  getStatus() {
    dd.httpRequest({
      url: app.userUrl + '/DingDing/Supervise/judgeIsSupervising',
      method: "GET",
      data: {
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        if (res.data.length != 0) {
          app.globalData.isSupervising = true,
            app.globalData.superviseSchoolId = res.data[0].schoolId
          app.globalData.superviseSchoolName = res.data[0].name
          app.globalData.superviseId = res.data[0].id
          this.setData({
            isSupervising: true,
          })
        }
      }
    })
    //日常巡查
    dd.httpRequest({
      url: app.userUrl + '/DingDing/Supervise/judgeIsSuddenSupervising',
      method: "GET",
      data: {
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        if (res.data.length != 0) {
          app.globalData.isSuddenSupervising = true
          app.globalData.suddensuperviseSchoolName = res.data[0].schoolname
          app.globalData.suddensuperviseSchoolId = res.data[0].schoolId
          app.globalData.suddensuperviseId = res.data[0].id
          this.setData({
            isSuddenSupervising: true
          })
        }
      }
    })
  },


  goToRegularSupervise: function (e) {
    if (app.globalData.isSuddenSupervising) {
      dd.showToast({
        content: '当前已有巡查任务进行中...',
      })
    } else {
      dd.navigateTo({
        url: `/subpages/pages/regularsupervise/regularsupervise`,
      })
    }
  },

  goToSuddenSupervise: function (e) {
    if (app.globalData.isSupervising) {
      dd.showToast({
        content: '当前已有巡查任务进行中...',
      })
    } else {
      dd.navigateTo({
        url: `/subpages/pages/suddensupervise/suddensupervise`,
      })
    }
  }


})